package myJs.register

import myJs.CpLayer.{loadComplete, startLoad}
import myJs.Implicits._
import myJs.api.Api
import myJs.assets.assetsCss
import myJs.cps._
import myJs.myPkg.jquery._
import myJs.myPkg.reactHookForm._
import myJs.myPkg.{BackstretchOptions, ReactRouterDOM}
import myJs.registerActive.RegisterActive
import org.scalajs.dom
import org.scalajs.dom.document
import org.scalajs.dom.html.Canvas
import org.scalajs.dom.window.localStorage
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Pojo.RegisterUserData
import shared.pojo._
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.web.html._
import typings.csstype.csstypeStrings

import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON

@react object Cp {

  type Props = Unit

  private val css = List(
    assetsCss.Layer,
    assetsCss.Sweetalert,
    assetsCss.BootstrapMin,
    assetsCss.BootstrapThemeMin,
    assetsCss.Doc,
    assetsCss.BootstrapDatepicker3,
    //    assetsCss.FontAwesomeMin,
    assetsCss.FontAwesomeMin,
    assetsCss.Components,
    assetsCss.BootstrapTable,
    assetsCss.Nprogress,
    assetsCss.TableFilter,
    assetsCss.Login5Min
  )

  case class GVerify(kind: String, height: Double, width: Double)

  private val css2 = assetsCss.My
  var canvas: Canvas = _
  type Ctx2D =
    dom.CanvasRenderingContext2D
  var gVerify: GVerify = _

  val component = FunctionalComponent[Props] { props =>
    val navigate = ReactRouterDOM.useNavigate()

    val useForm = ReactHookForm.useForm(
      UseFormOptions(
        mode = "onChange",
        resolver = yupResolver(Schema.schema)
      )
    )

    val (name, setName) = useState("")
    val (fullName, setFullName) = useState("")
    val (password, setPassword) = useState("")
    val (confirmPassword, setConfirmPassword) = useState("")
    val (unit, setUnit) = useState("")
    val (email, setEmail) = useState("")
    val (phone, setPhone) = useState("")
    val (captcha, setCaptcha) = useState("")
    val (code, setCode) = useState("")
    val (info, setInfo) = useState("")
    val (errorClass, setErrorClass) = useState("")

    object FTool {

      def nameChange = (v: String) => {
        setName(v)
      }

      def fullNameChange = (v: String) => {
        setFullName(v)
      }

      def passwordChange = (v: String) => {
        setPassword(v)
      }

      def confirmPasswordChange = (v: String) => {
        setConfirmPassword(v)
      }

      def unitChange = (v: String) => {
        setUnit(v)
      }

      def emailChange = (v: String) => {
        setEmail(v)
      }

      def phoneChange = (v: String) => {
        setPhone(v)
      }

      def captchaChange = (v: String) => {
        setCaptcha(v)
      }

      def formSubmit = useForm.handleSubmit((data: js.Dictionary[js.Any]) => {
        println(JSON.stringify(data))
        FTool.register()
      })

      def register = () => {
        val request = RegisterUserData(
          name = name,
          password = password,
          fullName = fullName,
          unit = unit,
          email = email,
          phone = phone
        )
        Api.register(request).map { response =>
          if (response.valid) {
            navigate(s"${RegisterActive.navigatePath}?email=${email}")
          }
        }
        ()
      }

      def captchaInit(divId: String) = {
        val conJq = $(s"#${divId}")
        val width = if (conJq.innerWidth() > 0) conJq.innerWidth() else 100
        val height = if (conJq.innerHeight() > 0) conJq.innerHeight() else 30
        canvas = document.createElement("canvas").asInstanceOf[Canvas]
        canvas.width = width.toInt
        canvas.height = height.toInt
        val canvasJq = $(canvas)
        val canvasId = "verifyCanvas"
        conJq.append(canvas)
        canvasJq.attr("id", canvasId)
        canvasJq.css("cursor", "pointer").html("您的浏览器版本不支持canvas")
        gVerify = GVerify(kind = "blend", height = height, width = width)
        refresh
        canvasJq.on(
          "click",
          () => {
            refresh
          }
        )
      }

      def getAllLetter = {
        val letterStr =
          "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"
        letterStr.split(",")
      }

      def randomNum(min: Double, max: Double) = {
        (math.random() * (max - min) + min).toInt
      }

      def randomColor(min: Int, max: Int) = {
        val r = randomNum(min, max)
        val g = randomNum(min, max)
        val b = randomNum(min, max)
        s"rgb($r,$g,$b)"
      }

      def refresh = {
        val numArr = "0,1,2,3,4,5,6,7,8,9".split(",")
        val letterArr = getAllLetter
        val ctx = canvas
          .getContext("2d")
          .asInstanceOf[Ctx2D]
        ctx.textBaseline = "middle"
        ctx.fillStyle = randomColor(180, 240)
        ctx.fillRect(0, 0, gVerify.width, gVerify.height)
        val txtArr = gVerify.kind match {
          case "blend"  => numArr ++ letterArr
          case "number" => numArr
          case _        => letterArr
        }
        val newCode = (1 to 4).map { i =>
          val txt = txtArr(randomNum(0, txtArr.length))
          ctx.font = randomNum(gVerify.height / 2, gVerify.height) + "px SimHei"
          ctx.fillStyle = randomColor(50, 160)
          ctx.shadowOffsetX = randomNum(-3, 3)
          ctx.shadowOffsetY = randomNum(-3, 3)
          ctx.shadowBlur = randomNum(-3, 3)
          ctx.shadowColor = "rgba(0, 0, 0, 0.3)"
          val x = gVerify.width / 5 * i
          val y = gVerify.height / 2
          val deg = randomNum(-30, 30)
          ctx.translate(x, y)
          ctx.rotate(deg * Math.PI / 180)
          ctx.fillText(txt, 0, 0)
          ctx.rotate(-deg * Math.PI / 180)
          ctx.translate(-x, -y)
          txt
        }.mkString
        setCode(newCode)
        (1 to 4).foreach { i =>
          ctx.strokeStyle = randomColor(40, 180)
          ctx.beginPath()
          ctx.moveTo(randomNum(0, gVerify.width), randomNum(0, gVerify.height))
          ctx.lineTo(randomNum(0, gVerify.width), randomNum(0, gVerify.height))
          ctx.stroke()
        }
        (0 to gVerify.width.toInt / 4).foreach { i =>
          ctx.fillStyle = randomColor(0, 255)
          ctx.beginPath()
          ctx.arc(
            randomNum(0, gVerify.width),
            randomNum(0, gVerify.height),
            1,
            0,
            2 * Math.PI
          )
          ctx.fill()
        }
      }

    }

    useEffect(
      () => {
        FTool.captchaInit("v_container")
      },
      List()
    )

    useEffect(
      () => {
        startLoad
        document.title = s"注册-LiveForest"
        loadComplete
      },
      List()
    )

    useEffect(
      () => {
        val images =
          List("login_3.jpg", "login_2.jpg", "login_1.jpg").map { name =>
            s"${Api.images}/${name}"
          }.toJSArray
        $(".login-bg").backstretch(
          images = images,
          options = BackstretchOptions(fade = 1e3, duration = 8e3)
        )
      },
      List()
    )

    div(
      className := "login",
      div(
        className := "user-login-5",
        div(
          className := "row bs-reset",
          div(
            className := "col-md-6 login-container bs-reset",
            TitleInfoCp(),
            div(
              className := "login-content",
              div(
                className := "register",
                h2(
                  className := "page-heading",
                  style := Style(fontSize = 25),
                  "注册"
                ),
                form(
                  style := Style(maxWidth = 700),
                  className := "registration-form form-horizontal",
                  onSubmit := FTool.formSubmit,
                  span(
                    style := Style(lineHeight = "35px"),
                    className := s"${errorClass}",
                    info
                  ),
                  FormGroupInlineCp(
                    useForm = useForm,
                    names = List("name", "fullName")
                  )(
                    InputInlineNoFormGroupCp(
                      useForm = useForm,
                      value = name,
                      label = "用户名",
                      placeHolder = "用户名",
                      name = s"name",
                      onChange = FTool.nameChange
                    ),
                    InputInlineNoFormGroupCp(
                      useForm = useForm,
                      value = fullName,
                      label = "姓名",
                      placeHolder = "姓名",
                      name = s"fullName",
                      onChange = FTool.fullNameChange
                    )
                  ),
                  FormGroupInlineCp(
                    useForm = useForm,
                    names = List("password", "confirmPassword")
                  )(
                    InputInlineNoFormGroupCp(
                      useForm = useForm,
                      value = password,
                      label = "密码",
                      placeHolder = "密码",
                      name = s"password",
                      onChange = FTool.passwordChange,
                      `type` = "password"
                    ),
                    InputInlineNoFormGroupCp(
                      useForm = useForm,
                      value = confirmPassword,
                      label = "确认密码",
                      placeHolder = "确认密码",
                      `type` = "password",
                      name = s"confirmPassword",
                      onChange = FTool.confirmPasswordChange
                    )
                  ),
                  FormGroupInlineCp(
                    useForm = useForm,
                    names = List("unit", "email")
                  )(
                    InputInlineNoFormGroupCp(
                      useForm = useForm,
                      value = unit,
                      label = "单位",
                      placeHolder = "单位",
                      name = s"unit",
                      onChange = FTool.unitChange
                    ),
                    InputInlineNoFormGroupCp(
                      useForm = useForm,
                      value = email,
                      label = "邮箱",
                      placeHolder = "邮箱",
                      name = s"email",
                      onChange = FTool.emailChange
                    )
                  ),
                  InputInlineCp(
                    useForm = useForm,
                    value = phone,
                    label = "手机",
                    placeHolder = "手机",
                    name = s"phone",
                    onChange = FTool.phoneChange
                  ),
                  FormGroupInlineCp(useForm = useForm, names = List("captcha"))(
                    InputInlineNoFormGroupCp(
                      useForm = useForm,
                      value = captcha,
                      label = "验证码",
                      placeHolder = "验证码",
                      name = s"captcha",
                      onChange = FTool.captchaChange
                    ),
                    div(
                      div(
                        style := Style(height = 34, width = 180),
                        className := "col-sm-5",
                        id := "v_container"
                      ),
                      PureInputCp(
                        useForm = useForm,
                        name = s"code",
                        value = s"${code}",
                        `type` = "hidden"
                      )
                    )
                  ),
                  div(
                    className := "actions",
                    button(
                      style := Style(width = "100%"),
                      `type` := "submit",
                      className := "btn btn-primary btn-lg",
                      s" 注册"
                    )
                  )
                )
              )
            ),
            div(
              className := "login-footer",
              div(
                className := "row bs-reset",
                div(
                  className := "col-xs-12 bs-reset",
                  div(
                    className := "login-copyright text-right",
                    p(
                      style := Style(color = "black"),
                      "版权所有2018 深圳市绘云生物科技有限公司 All Rights Reserved"
                    )
                  )
                )
              )
            )
          ),
          div(className := "col-md-6 bs-reset", div(className := "login-bg"))
        )
      )
    )
  //						 action="@routes.AppController.register">

  }

}
